package org.farm2.base.db;

import org.apache.ibatis.jdbc.SQL;
import org.farm2.tools.db.DataQuery;
import org.farm2.tools.db.DataResult;
import org.farm2.tools.db.commons.QueryRule;
import org.farm2.tools.i18n.I18n;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 格式化查询构造器
 */
public class DataSQLBuilder {

    public static String getInsertSql(Map<String, Object> values, String tableName) {
        String sql = new SQL() {{
            INSERT_INTO(tableName);
            for (Map.Entry<String, Object> entry : values.entrySet()) {
                VALUES(entry.getKey(), "#{values." + entry.getKey() + "}");
            }
        }}.toString();
        return sql;
    }


    public String getDeleteSql(String tableName, List<QueryRule> rules) {

        StringBuffer whereSql = new StringBuffer(" WHERE 1=1");
        if (rules == null || rules.size() <= 0) {
            throw new RuntimeException(I18n.msg("刪除语句必须添加WHERE条件"));
        }
        for (QueryRule rule : rules) {
            whereSql.append(rule.getSql());
        }
        String sql = new StringBuffer().append("DELETE FROM ").append(tableName).append(whereSql).toString();
        return sql;
    }


    public String getDataSqlByRules(String tableName, List<QueryRule> rules) {

        StringBuffer whereSql = new StringBuffer(" WHERE 1=1");
        if (rules == null) {
            rules = new ArrayList<>();
        }
        for (QueryRule rule : rules) {
            whereSql.append(rule.getSql());
        }
        String sql = new StringBuffer().append("SELECT * FROM ").append(tableName).append(whereSql).toString();
        return sql;
    }

    public String getUpdateSql(Map<String, Object> values, String tableName, String primaryKey) {

        Map<String,Object> fields=new HashMap<>(values);
        Object id = fields.remove(primaryKey); // 移除主键，因为它不应该出现在 SET 子句中
        if (id == null) {
            id = fields.remove(primaryKey.toUpperCase());
        }
        if (id == null) {
            id = fields.remove(primaryKey.toLowerCase());
        }
        if (id == null) {
            throw new IllegalArgumentException("The 'id' field is required for updating records.");
        }
        String sql = new SQL() {{
            UPDATE(tableName);

            for (Map.Entry<String, Object> entry : fields.entrySet()) {

                if (entry.getValue() != null) {
                    SET(entry.getKey() + " = #{values." + entry.getKey() + "}");
                }
            }

            WHERE("id = #{values."+primaryKey+"}");
        }}.toString();
        return sql;
    }
}
